<template>
    <div class='container'>
        <div class="drawer-container">
            <t-drawer v-model:visible="visible" :placement="placement" :size="size"
                :header="book_info_form._id ? '编辑书籍' : '添加书籍'" :footer="false">
                <t-form :model="book_info_form">
                    <t-form-item label="书籍名称" prop="name">
                        <t-input v-model="book_info_form.name" placeholder="请输入书籍名称" />
                    </t-form-item>
                    <t-form-item label="书籍作者" prop="author">
                        <t-input v-model="book_info_form.author" placeholder="请输入书籍作者" />
                    </t-form-item>
                    <t-form-item label="封面" prop="cover">
                        <t-input v-model="book_info_form.cover" placeholder="请输入书籍封面" />
                    </t-form-item>
                    <t-divider></t-divider>
                    <t-form-item label="书籍出版社" prop="publisher">
                        <t-input v-model="book_info_form.publisher" placeholder="请输入书籍出版社" />
                    </t-form-item>

                    <t-form-item label="出版时间" prop="publish_time">
                        <t-date-picker borderless clearable v-model="book_info_form.publish_time" />
                    </t-form-item>
                    <t-form-item label="ISBN" prop="isbn">
                        <t-input v-model="book_info_form.isbn" placeholder="请输入ISBN" />
                    </t-form-item>
                    <t-form-item label="书籍字数" prop="word_count">
                        <t-input v-model="book_info_form.word_count" placeholder="请输入书籍字数" />
                    </t-form-item>
                    <t-form-item label="书籍摘要" prop="summary">
                        <t-textarea v-model="book_info_form.summary" placeholder="请输入书籍摘要" />
                    </t-form-item>
                    <t-divider />
                    <t-form-item label="豆瓣首页" prop="douban_home">
                        <t-input v-model="book_info_form.urls.douban_home" placeholder="请输入豆瓣首页" />
                    </t-form-item>
                    <t-form-item label="得到主页" prop="dedao_home">
                        <t-input v-model="book_info_form.urls.dedao_home" placeholder="请输入得到主页" />
                    </t-form-item>
                    <t-form-item label="听书主页" prop="dedao_listen_home">
                        <t-input v-model="book_info_form.urls.dedao_listen_home" placeholder="请输入听书主页" />
                    </t-form-item>
                </t-form>

                <div class="submit-btn">
                    <t-button @click="handleAddBook" size="large">提交</t-button>
                    <t-button @click="visible = false" size="large">取消</t-button>
                </div>
            </t-drawer>
        </div>
        <div class="search-container">
            <t-input clearable size="large" placeholder="请输入书籍名称/作者" v-model="query" />
            <t-button @click="handleAddBookClick" size="large">添加书籍</t-button>
        </div>
        <div class="table-content">
            <t-table row-key="_id" :data="data" :columns="columns"  hover
               size="small" :pagination="pagination"
                 cell-empty-content="-" lazy-load 
                @page-change="handlePageChange"
                :expand-on-row-click="expandOnRowClick"
                :expanded-row-keys="expandedRowKeys"
                @expand-change="handleExpandChange" >
                <template #word_count="{ row }">{{ row.word_count }}千字</template>
                <template #activate="{ row }">{{ row.activate ? '已激活' : '未激活' }}</template>
                <template #options="{ row }">
                    <div class="options-btn-group">
                        <t-button  size="small" theme="primary" @click="handleEditBook(row._id)">编辑</t-button>
                        <t-button  size="small" theme="danger" @click="handleDeleteBook(row._id)">删撤</t-button>
                        <t-button  size="small" theme="success" @click="handleViewBook(row._id)">查看</t-button>
                    </div>
                </template>
            <!-- 展开行内容（核心） -->
            <template #expandedRow="{ row }">
                <div class="more-detail">
                   <t-button size="small" theme="primary" :href="'https://www.dedao.cn/search/result?q='+row.name" target="_blank">去得到</t-button>
                   <t-button size="small" theme="primary" :href="'https://search.bilibili.com/all?keyword='+row.name" target="_blank">去B站</t-button>
                </div>
            </template>
            </t-table>
        </div>
    </div>
</template>
<script setup lang='ts'>
import { onMounted, ref } from 'vue';
import { MessagePlugin, type DrawerProps, type RadioGroupProps } from 'tdesign-vue-next';
import { getBookByIdAPI, addBookAPI, deleteBookAPI, getBookListAPI } from '@/api/media_book';
// 抽屉部分
type BookUrlModel = {
    douban_home: string
    dedao_home: string
    dedao_listen_home: string
}
type BookInfoModel = {
    _id?: string
    name: string
    author: string
    cover: string
    publisher: string
    publish_time: string
    isbn: string
    word_count: number
    summary: string
    urls: BookUrlModel
}
const book_info_form = ref<BookInfoModel>({
    "name": "",
    "author": "",
    "cover": "",
    "publisher": "",
    "publish_time": "",
    "isbn": "",
    "word_count": 0,
    "summary": "",
    "urls": {
        "douban_home": "",
        "dedao_home": "",
        "dedao_listen_home": ""
    }
})
const visible = ref(false);
const size = ref<RadioGroupProps['defaultValue']>('large');
const placement = ref<DrawerProps['placement']>('right');

const handleAddBook = async () => {
    console.log(book_info_form.value);
    const res = await addBookAPI(book_info_form.value);
    // @ts-ignore
    if (res.code === 200) {
        // 成功添加书籍后，刷新书籍列表
        // @ts-ignore
        MessagePlugin.success(res.msg + '，书籍ID为：' + res.data.id);
        // 刷新书籍列表
        await getBookList();
        visible.value = false;
    } else {
        // @ts-ignore
        MessagePlugin.error(res.msg);
    }

}

const getBookById = async (book_id: string) => {
    const res = await getBookByIdAPI(book_id);
    console.log(res)
    // @ts-ignore
    if (res.code === 200) {
        // @ts-ignore
        book_info_form.value = res.data;
    } else {
        // @ts-ignore
        MessagePlugin.error(res.msg);
    }
}



// 表格部分
import type { TableProps } from 'tdesign-vue-next';
const query = ref('');
// 表格数据
const data = ref([]);
const expandOnRowClick = ref(false);
const expandedRowKeys = ref<string[]>(['2']);

// 展开状态变更
const handleExpandChange = (keys: string[]) => {
    expandedRowKeys.value = keys;
};

const columns = ref<TableProps['columns']>([
    { colKey: 'name', title: '书名', width: '100', ellipsis: true, },
    { colKey: 'author', title: '作者', width: '100', ellipsis: true, },
    { colKey: 'publisher', title: '出版社', width: '100', ellipsis: true, },
    { colKey: 'isbn', title: 'ISBN', width: '50', ellipsis: true, },
    { colKey: 'word_count', title: '字数', width: '50', ellipsis: true, },
    { colKey: 'publish_time', title: '出版时间', width: '100', ellipsis: true, },
    { colKey: 'activate', title: '状态', width: '50', ellipsis: true, },
    { colKey: "options", title: '操作', width: '120'},
]);


// 添加ref后，访问api，改变total，data的改变才会显示
const pagination = ref<TableProps['pagination']>({
    defaultCurrent: 1,
    defaultPageSize: 10,
    total: data.value.length, // 使用实际数据长度
});
const handleEditBook = async (book_id: string) => {
    // console.log(book_id);
    visible.value = true;
    // 填充表单数据
    await getBookById(book_id);

}

const getBookList = async () => {

    query.value = query.value.trim();
    // @ts-ignore
    const res = await getBookListAPI(pagination.value.defaultCurrent || 1, pagination.value.defaultPageSize || 10, query.value, true);

    // @ts-ignore
    if (res.code === 200) {
        // @ts-ignore
        data.value = res.data.list;
        // @ts-ignore
        pagination.value.total = res.data.total;
    }
}
const handleDeleteBook = async (book_id: string) => {
    console.log(book_id);
    const res = await deleteBookAPI(book_id);
    // @ts-ignore
    if (res.code === 200) {
        // @ts-ignore
        MessagePlugin.success(res.msg);
        // 刷新书籍列表
        getBookList();
    } else {
        // @ts-ignore
        MessagePlugin.error(res.msg);
    }
}
const handleAddBookClick = () => {
    visible.value = true;
    // 清空表单数据
    // @ts-ignore
    book_info_form.value = {
        name: '',
        author: '',
        cover: '',
        publisher: '',
        publish_time: '',
        isbn: '',
        word_count: 0,
        summary: '',
        urls: {
            douban_home: '',
            dedao_home: '',
            dedao_listen_home: '',
        },
    };
    // @ts-ignore
    // book_info_form.value ={}
}

const handlePageChange = async (page: number) => {
    console.log('分页变更:', page);
    // @ts-ignore
    pagination.value.defaultCurrent = page.current;
    await getBookList()
}

import router from '@/router';
const handleViewBook = async (book_id: string) => {
    // 跳转到路由 : /tool/book-detail/:book_id
    router.push({ name: 'kg-book-detail', params: { book_id } });
}
onMounted(async () => {
    await getBookList()
    // getBookById(1);
})
</script>
<style lang='scss' scoped>
.container {
    width: 90%;
    margin: 0 auto;
    display: flex;
    flex-direction: column;
    gap: 10px;
}

.drawer-container {
    .submit-btn {
        margin-top: 20px;
        display: flex;
        justify-content: center;
        gap: 10px;
    }
}

.search-container {
    width: 50%;
    display: flex;
    margin: 0 auto;
    align-items: center;
    gap: 10px;
}

.table-content {
    .options-btn-group {
        display: flex;
        justify-content: center;
        gap: 5px;
    }
    .more-detail {
        display: flex;
        // justify-content: center;
        gap: 10px;
    }
}
</style>